package com.guxingke.typecho4j.widget.handle.user;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.route.DispatcherStrategy;
import com.guxingke.typecho4j.route.Route;
import com.guxingke.typecho4j.route.Routes;
import com.guxingke.typecho4j.widget.WidgetHandle;
import com.guxingke.typecho4j.widget.provider.UserBaseWidget;
import com.jfinal.core.Controller;

/**
 * 用户退出登录的处理组件
 * 
 * @author guxingke
 *
 */
public class LogoutHandleWidget extends UserBaseWidget implements WidgetHandle {

	@Override
	public void handle(Controller controller) throws Typecho4jException {
		HttpSession session = controller.getSession();

		session.removeAttribute("user");
		deleteCookie(controller.getResponse(), "user");

		controller.redirect("/index");
	}

	private void deleteCookie(HttpServletResponse response,
			String cookieName) {
		Cookie cookie = new Cookie(cookieName, "");
		cookie.setPath("user");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	@Override
	public void configRoute(Routes routes) {
		Route logoutRoute = new Route("logout", this.getClass(),
				"/index", DispatcherStrategy.REDIRECT);
		routes.addRoute(logoutRoute);
	}

}
